package com.dance.sharevalidator.validation.validator;

import com.dance.sharevalidator.config.ValidatorUtils;
import com.dance.sharevalidator.exception.ValidListException;
import com.dance.sharevalidator.validation.ValidList;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.ConstraintViolation;
import java.util.*;

public class ValidListValidator implements ConstraintValidator<ValidList, List> {
    Class<?>[] groupings;

    boolean quickFail;

    @Override
    public void initialize(ValidList constraintAnnotation) {
        groupings = constraintAnnotation.groupings();
        quickFail = constraintAnnotation.quickFail();
    }

    @Override
    public boolean isValid(List collection, ConstraintValidatorContext constraintValidatorContext) {
        if (collection == null) {
            return true;
        }
        Map<Integer, Set<ConstraintViolation<Object>>> errors = new HashMap<>();
        for (int i = 0; i < collection.size(); i++) {
            Object o = collection.get(i);
            // 有几个错误, 就有几个元素
            Set<ConstraintViolation<Object>> validate = ValidatorUtils.validator.validate(o, groupings);
            if (null != validate && 0 != validate.size()) {
                errors.put(i, validate);
                // 快速失败
                if (quickFail) {
                    break;
                }
            }
        }
        if (errors.size() > 0) {
            // 通过抛异常的手段来 让我们自己的全局异常拦截器拦截, 绕过Validation的默认报错
            throw new ValidListException(errors);
        }
        return true;
    }
}
